<template>
  <div id="add">
    <!-- 头部 -->
    <div class="navebar">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="点位搜索">
          <el-input
            v-model="formInline.taskCode"
            placeholder="请输入"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="区域搜索">
          <el-select
            v-model="formInline.status"
            placeholder="请选择"
            style="width: 200px"
          >
            <el-option
              v-for="(item, index) in taskSty"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSubmit">
            查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格新建按钮 -->
    <div class="box">
      <div class="btn">
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          class="btn1"
          @click="addClick"
        >新建</el-button>
      </div>

      <!-- 表格 -->
      <div class="tabel">
        <el-table
          v-loading="loading"
          :data="SearchList"
          style="width: 100%"
          height="419"
          :header-cell-style="{
            //标题头部的颜色
            background: '#f5f7fa',
            height: '40px',
          }"
        >
          <el-table-column fixed type="index" label="序号" width="100" />
          <el-table-column prop="name" label="点位名称" width="160" />
          <el-table-column
            prop="region.name"
            label="所在区域"
            width="180"
          />
          <el-table-column
            prop="businessType.name"
            label="商圈类型"
            width="140"
          />
          <el-table-column
            prop="ownerName"
            label="合作商"
            width="160"
          />
          <el-table-column
            prop="addr"
            label="详细地址"
            width="265"
          />
          <el-table-column
            fixed="right"
            label="操作"
            width="240"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="medium "
                @click="inspectClick(scope.row)"
              >查看详情</el-button>
              <el-button
                type="text"
                size="medium"
                @click="handleClick(scope.row)"
              >修改</el-button>
              <el-button
                type="text"
                size="medium"
                style="color: red"
                @click="delClick"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 实现分页
        current-page 当前页数
        page-size 每页显示个数
        total 总条目数
        current-change 页面改变时会触发
        prev-text="上一页"
        next-text="下一页"
         -->
        <div class="block">
          <el-pagination
            background
            :current-page.sync="pageOption.pageIndex"
            :page-size="pageOption.pagesize"
            layout="total,  pager, prev, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 新建弹出框 -->
    <el-dialog
      :title="title"
      :visible.sync="centerDialogVisible"
      width="50%"
      :before-close="closeFn"
    >
      <!-- 表单内容 -->
      <el-form
        ref="departRef"
        :model="departForm"
        :rules="departRules"
        label-width="120px"
      >
        <el-form-item label="点位名称" prop="name">
          <el-input
            v-model="departForm.name"
            style="width: 85%"
            placeholder="请输入"
            maxlength="15"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="所在区域" prop="regionId">
          <el-select
            v-model="departForm.regionId"
            style="width: 85%"
            placeholder="请选择"
          >
            <el-option
              v-for="item in taskSty"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属商圈" prop="businessId">
          <el-select
            v-model="departForm.businessId"
            style="width: 85%"
            placeholder="请选择"
          >
            <el-option
              v-for="item in district"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="归属合作商" prop="ownerId">
          <el-select
            v-model="departForm.ownerId"
            style="width: 85%"
            placeholder="请选择"
          >
            <el-option
              v-for="item in partner"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="areaCode">
          <el-cascader
            v-model="departForm.areaCode"
            size="large"
            :options="options"
            style="width: 85%"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item label="" prop="addr">
          <el-input
            v-model="departForm.addr"
            style="width: 85%"
            placeholder="请输入详细地址"
            type="textarea"
            rows="3"
            maxlength="60"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button class="btnquxiao" @click="closeFn">取 消</el-button>
        <el-button
          type="primary"
          class="btn1"
          @click="submitWork(departForm)"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 查看详情弹出框 -->
    <el-dialog
      title="点位详情"
      :visible.sync="regional"
      width="50%"
      @close="regional=false"
    >
      <!-- 内容 -->
      <template>
        <el-table :data="tableData" height="350" stripe style="width: 100%">
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column prop="innerCode" label="机器编号" width="140" />
          <el-table-column label="设备状态" width="140">
            <template #default="scope">
              {{ vm[scope.row.vmStatus]||'未知' }}
            </template>
          </el-table-column>
          <el-table-column label="最后一次供货时间" width="200">
            <template #default="scope">
              {{ formatDate(scope.row.createTime)||'未知' }}
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-dialog>
  </div>
</template>

<script>
//  https://www.npmjs.com/package/element-china-area-data
import { getRegionListApi, serchNodeListApi, getDistrictListApi, getPenterListApi, addPenterListApi, alterPenterListApi, vmPenterApi } from '@/api'
// import { Message } from 'element-ui'
import dayjs from 'dayjs'
import { regionData } from 'element-china-area-data'
import { Message } from 'element-ui'
export default {
  data() {
    return {
      loading: false,
      regional: false,
      centerDialogVisible: false,
      options: regionData, // 下拉城市
      selectedOptions: [], // 下拉城市选择
      // 搜索框
      formInline: {
        taskCode: ''
      },
      task: [],
      taskSty: [], // 所在区域
      district: [], // 所在商圈
      partner: [], // 归属合作商
      address: [], // 详细地址
      // 新增点位数据
      departForm: {
        name: '', // 名称
        addr: '', // 详细地址
        areaCode: '', // 最后一级区域Id
        regionId: '', // 所属区域Id
        businessId: '', // 所属商圈Id
        ownerId: '' // 合作商ID
      },
      // 表单校验
      departRules: {
        name: [{ required: true, message: '区域名称不能为空', trigger: ['blur'] }],
        addr: [{ required: true, message: '请填写详细地址', trigger: ['blur'] }],
        areaCode: [{ required: true, message: '请选择地址', trigger: ['blur'] }],
        regionId: [{ required: true, message: '请选择区域', trigger: ['blur'] }],
        businessId: [{ required: true, message: '请选择商圈', trigger: ['blur'] }],
        ownerId: [{ required: true, message: '请选择合作商', trigger: ['blur'] }]
      },
      // 搜索传入的数值
      pageOption: {
        pageIndex: 1,
        pagesize: 10,
        name: ''
      },
      SearchList: [],
      currentPage1: 10,
      total: 0,
      tableData: [], // 查看详情表格
      // 查看详情状态枚举
      vm: {
        0: '未投放',
        1: '运营',
        3: '撤机'
      }
    }
  },
  computed: {
    title() {
      return this.departForm.id ? '修改点位' : '新增点位'
    }
  },
  async created() {
    // 区域列表调用
    this.getRegionList()
    this.getRegion()
  },
  methods: {
    // 页面表格列表封装
    async getRegionList() {
      this.loading = true
      const { data } = await serchNodeListApi(this.pageOption)
      console.log(data)
      this.SearchList = data.currentPageRecords
      this.total = +data.totalCount
      this.loading = false
      // 所属商圈
      const res = await getDistrictListApi()
      this.district = res.data
      // 归属合作商
      const res2 = await getPenterListApi({
        pageIndex: 1,
        pageSize: 10000
      })
      this.partner = res2.data.currentPageRecords
      console.log(res2.data)
    },

    // 区域列表查询封装
    async getRegion() {
      const { data } = await getRegionListApi({
        pageIndex: 1,
        pageSize: 100000
      })
      this.taskSty = data.currentPageRecords
    },

    // 查询功能
    // 绑定查询事件，在下面声明点击事件
    // 封装数据请求接口、引入、使用
    // 点击查询按钮，将数据传给子组件表格
    // 子组件接收，并进行数据请求实现查询功能
    onSubmit() {
      console.log('submit!')
      this.pageOption.name = this.formInline.taskCode
      this.getRegionList(this.pageOption)
    },

    // 新建按钮
    // 注册新建按钮的点击事件
    // 点击新建展示新建弹窗
    // 准备新建弹窗dom结构
    // 封装接口，引入接口
    // 请求表单下拉列表数据
    async addClick() {
      this.centerDialogVisible = true
      // 所在区域
      this.getRegion()
    },

    // 新建提交
    // 声明点击事件
    // 对表单进行校验
    // 封装接口，引入接口
    // 在点击确定的时候请求接口，传入数据
    // 判断：如果传入的参数有id的话，说明是修改按钮的数据回显，点击确认修改数据
    // 请求修改的接口
    // 如果没有的话，请求添加的接口
    // 对弹窗内的input框进行兜底校验
    // 添加成功，提示用户
    // 关闭弹窗，清空表单
    async submitWork(val) {
      // 获取合作商下拉框的合作商名字
      let obj = {}
      obj = this.partner.find(item => item.id === this.departForm.ownerId)
      this.$refs.departRef.validate(async(vaild) => {
        if (!vaild) return
        this.departForm.areaCode = this.departForm.areaCode.pop()
        console.log(val)
        if (val.id) {
          console.log(1)
          await alterPenterListApi({
            ...this.departForm,
            id: val.id,
            createUserId: 1,
            ownerName: obj.name
          })
          Message.success('修改点位成功')
        } else {
          console.log(val)
          await addPenterListApi({
            ...this.departForm,
            createUserId: 1,
            ownerName: obj.name
          })
          Message.success('新增点位成功')
        }
        this.centerDialogVisible = false
        this.departForm = {
          name: '',
          addr: '',
          areaCode: '',
          regionId: '',
          businessId: '',
          ownerId: ''
        }
        this.getRegionList()
      })
    },

    // 点击取消关闭弹窗、清除表单
    closeFn() {
      this.centerDialogVisible = false
      this.regional = false
      this.$refs.departRef.resetFields()
      this.departForm = {
        name: '',
        addr: '',
        areaCode: '',
        regionId: '',
        businessId: '',
        ownerId: ''
      }
    },

    // 点击查看详情功能
    // 准备查看详情弹窗的dom结构
    // 绑定查看详情按钮事件
    // 声明事件
    // 封装数据请求接口、引入
    // 点击详情按钮打开查看详情弹窗
    // 请求数据，实现弹窗数据显示
    // 提示用户
    // 关闭弹窗
    async inspectClick(val) {
      console.log(val)
      this.regional = true
      const { data } = await vmPenterApi(val.businessId)
      this.tableData = data
      console.log(data)
    },

    // 点击修改详情
    // 展示查看详情的弹窗组件
    // 传入当前行的数据
    // 实现数据回显
    // 点击确认修改，将该项的id传入修改接口
    // 实现修改
    // 关闭弹窗
    // 清空表单
    // 重新调用数据请求接口、更新页面
    async handleClick(val) {
      this.centerDialogVisible = true
      this.departForm = val
    },

    // 点击删除
    delClick() {
      this.$message({
        message: '您没有删除操作权限哦！',
        type: 'warning'
      })
    },

    // 格式化时间
    formatDate(value) {
      return dayjs(value).format('YYYY-MM-DD hh:mm:ss')
    },

    // 实现分页
    handleCurrentChange(val) {
      this.loading = true
      this.pageOption.pageIndex = val
      this.getRegionList()
      this.loading = false
    }
  }
}
</script>

<style lang="scss">
#add {
  overflow: hidden;
  background-color: #f8fafd;
}
.navebar {
  margin: 20px 19px 0;
  padding-top: 14px;
  padding-left: 18px;
  height: 64px;
  background-color: #fff;
}
// 表格
.box {
  margin: 20px 19px 0;
  padding: 17px 0 1px 18px;
  background-color: #fff;
}
// 按钮
.btn1 {
  background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
  border: #f8fafd;
  height: 35px;
}
// 内容
.el-descriptions {
  padding: 0px 0px 0px 30px;
}
.el-dialog__footer {
  margin-top: -38px;
  padding: 10px 212px 20px;
}
.dialog-footer {
  margin-top: 10px;
}
.btnquxiao {
  margin-right: 20px;
  height: 37px;
}
.button {
  background-color: #fbf4f0;
  border: #f8fafd;
  color: #f97138;
}
// 分页器
.block {
  margin: 20px 0;
}
.tabel {
  margin-top: 19px;
}
.btn-prev {
  margin-left: 100px;
}
// 区域详情弹窗
.box1 {
  margin-left: 56px;
  margin-top: -5px;
  font-size: 15px;
}
.box1 span {
  margin-right: 25px;
}
.box2 {
  // display: flex;
  margin-top: 30px;
}
.box2 .span{
  margin-top: -14px;
}
.el-dialog__title {
  line-height: 22px;
  font-size: 17px;
  font-weight: 600;
  color: #333;
}
.el-dialog__body{
    padding: 30px 35px;
}
</style>
